﻿using HDS.Data;
using HDS.IService.Sys;
using HDS.Model.Entity.Sys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HDS.Service.Sys
{
    public class SysRoleService : ISysRoleService
    {
        private SysDbContext db = new SysDbContext();

        public async Task Delete(int roleId)
        {
            await db.SysRole.DeleteAsync(e => e.RoleId == roleId);
        }

        public async Task<SysRole> Get(int roleId)
        {
            return await db.SysRole.GetByIdAsync(roleId);
        }

        public async Task<List<SysFun>> GetFuns(int roleId)
        {
            return await db.Db.Queryable<SysRoleFun, SysFun>((rf, f) => new JoinQueryInfos(
                 JoinType.Inner, rf.FunId == f.FunId
            )).Where(rf => rf.RoleId == roleId).Select<SysFun>().ToListAsync();
        }

        public async Task<List<SysRole>> GetList()
        {
            return await db.SysRole.GetListAsync();
        }

        public async Task Save(SysRole sysRole)
        {
            if (sysRole.RoleId == 0)
                await db.SysRole.InsertAsync(sysRole);
            else
                await db.SysRole.UpdateAsync(sysRole);
        }

        public async Task SetFuns(int roleId, int[] funIds)
        {
            await db.SysRoleFun.DeleteAsync(e => e.RoleId == roleId);

            if (funIds.Any())
            {
                var userRoles = funIds.Select(e => new SysRoleFun { Id = 0, RoleId = roleId, FunId = e }).ToArray();
                await db.SysRoleFun.InsertRangeAsync(userRoles);
            }
        }
    }
}
